package com.puzzlebazar.client.main.control;

import java.util.HashMap;

import com.puzzlebazar.client.main.model.PuzzleList;
import com.puzzlebazar.client.main.model.PuzzleListInfo;
import com.puzzlebazar.client.main.model.PuzzleListInfoFactory;
import com.puzzlebazar.client.main.model.PuzzleListInfoSimple;
import com.puzzlebazar.client.main.view.GenericListView;
import com.puzzlebazar.client.main.view.MainView;
import com.puzzlebazar.client.main.view.PuzzleListView;
import com.puzzlebazar.client.user.UserModel;

public class PuzzleListState extends MainState {
	
	public static final String STATE_TOKEN = "PuzzleList";
	
	private final PuzzleList puzzleList;
	
	private GenericListView puzzleListView = null;

	private boolean isInside = false;
	
	public PuzzleListState( UserModel model, MainView view, MainController controller ) {
		super( model, view, controller );
		puzzleList = new PuzzleList( model );
	}


	@Override
	public String getStateToken() {
		return STATE_TOKEN;
	}

	/**
	 * Get the current parameters of the state provided a puzzleId
	 * 
	 * @param listInfo Information on the puzzle list to get 
	 * @return The parameters of the state
	 */
	public static HashMap<String,String> getParams( PuzzleListInfo listInfo ) {
		return listInfo.getParams();
	}

	@Override
	public HashMap<String,String> getParams() {
		return getParams( puzzleList.getListInfo() );
	}

	/**
	 * Sets the parameters for the puzzle to load
	 * 
	 * @param listInfo Information on the puzzle list to get
	 */
	public void setParams( PuzzleListInfo listInfo ) {
		puzzleList.setListInfo(listInfo);
		if( isInside ) {
			setTitle();
			puzzleList.refresh();
			puzzleList.notifyObservers();	
		}
	}

	@Override
	public void setParams( HashMap<String,String> params ) throws Exception {
		try {
			setParams( 
					PuzzleListInfoFactory.getInstance().createPuzzleListInfo(params) );
		}
		catch( Exception exception ) {
			setParams( PuzzleListInfoSimple.getInstance(PuzzleListInfoSimple.ListType.ALL_PUZZLES) );
			throw new Exception( "Invalid parameters" );
		}
	}
	

	@Override
	public void enter() {
		isInside = true;
		setTitle();
		puzzleList.refresh();
		puzzleList.notifyObservers();
		if( puzzleListView == null )
			puzzleListView = new PuzzleListView( puzzleList, controller );		
		
		view.setMainWidget( puzzleListView );
	}

	@Override
	public void exit() {
		isInside = false;
	}


	/**
	 * Sets the main panel title
	 */
	private void setTitle() {
		view.setMainPanelTitle( puzzleList.getName() );
	}


	@Override
	public void release() {
		super.release();
		puzzleList.release();
	}	
	
}
